import React from 'react';
import { createRoot } from 'react-dom/client';
import '../styles/dialog.css';
import { CloseIcon } from './Icons';

interface DialogProps {
  title: string;
  content: string;
  onConfirm?: () => void;
  onCancel?: () => void;
  showCancel?: boolean;
  confirmText?: string;
}

const Dialog: React.FC<DialogProps> = ({ title, content, onConfirm, onCancel, showCancel, confirmText }) => {
  const handleConfirm = () => {
    onConfirm?.();
    unmount();
  };

  const handleCancel = () => {
    onCancel?.();
    unmount();
  };

  const unmount = () => {
    const container = document.getElementById('dialog-container');
    if (container) {
      document.body.removeChild(container);
    }
  };

  return (
    <div className="dialog-overlay">
      <div className="dialog-container">
        <div className="dialog-header">
          <h3>{title}</h3>
          <button onClick={handleCancel} className="btn-close"><CloseIcon/></button>
        </div>
        <div className="dialog-body">
          <p>{content}</p>
        </div>
        <div className="dialog-footer">
          {showCancel && <button onClick={handleCancel} className="btn-cancel">取消</button>}
          <button onClick={handleConfirm} className="btn-confirm">{confirmText || '确认'}</button>
        </div>
      </div>
    </div>
  );
};

export const showDialog = (props: DialogProps) => {
  const container = document.createElement('div');
  container.id = 'dialog-container';
  document.body.appendChild(container);
  const root = createRoot(container);
  root.render(<Dialog {...props} />);
}; 